﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;

namespace UpdataStart
{

    public class DownloadTool
    {
        //下载更新xml文件 
        public static void DownloadFile(string localFolder, string remoteFolder, string fileName)
        {
            string url = remoteFolder + fileName;
            string path = localFolder + fileName;
            string dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            var wc = new WebClient();
            wc.DownloadFile(url, path);
        }

        public static string FormatFileSizeDescription(int bytes)
        {
            if (bytes > 1024 * 1024)
                return string.Format("{0}M", Math.Round((double)bytes / (1024 * 1024), 2, MidpointRounding.AwayFromZero));
            if (bytes > 1024)
                return string.Format("{0}K", Math.Round((double)bytes / 1024, 2, MidpointRounding.AwayFromZero));
            return string.Format("{0}B", bytes);
        }

        //文件更新过的下载
        public static void DownloadFile(string localFolder, string remoteFolder, string fileName, ProgressBar bar, Label lblSize)
        {
            // Thread.Sleep(5000);//真正用的时候把此行注释掉，现在是为了模拟进度条
            string url = remoteFolder + "/" + fileName;
            string path = localFolder + fileName;
            string dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            WebRequest req = WebRequest.Create(url);            
            WebResponse res = req.GetResponse();       //此处不能用于FTP服务器 System.Net.FtpWebRequest

            if (res.ContentLength == 0)
                return;

            long fileLength = res.ContentLength;
            string totalSize = FormatFileSizeDescription(bar.Maximum);
            using (Stream srm = res.GetResponseStream())
            {
                var srmReader = new StreamReader(srm);
                var bufferbyte = new byte[fileLength];
                int allByte = bufferbyte.Length;
                int startByte = 0;
                while (fileLength > 0)
                {
                    int downByte = srm.Read(bufferbyte, startByte, allByte);
                    if (downByte == 0)
                    {
                        break;
                    }
                    ;
                    startByte += downByte;
                    allByte -= downByte;
                    int progress = bar.Value + downByte;
                    progress = progress > bar.Maximum ? bar.Maximum : progress;
                    bar.Value = progress;

                    lblSize.Text = string.Format("已完成{0}/{1}", FormatFileSizeDescription(progress), totalSize);
                }
                var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(bufferbyte, 0, bufferbyte.Length);
                srm.Close();
                srmReader.Close();
                fs.Close();
            }
        }
    }

    internal class AppTool
    {
        /// <summary>
        /// 启动主程序进程
        /// </summary>
        /// <param name="appName"></param>
        public static void Start(string appName)
        {
            try
            {
                Process.Start(appName, "ok");
            }
            catch (Exception )
            {
                throw new Exception("找不到指定文件" + appName + "请配置ReleaseList.xml文件");
            }
        }

       // 删除这个目录下的所有子目录和文件
        internal static void DeleteTempFolder(string folder)
        {
            try
            {
               // Directory.Delete(folder, true);

                //删除这个目录下的所有子目录
                if (Directory.GetDirectories(folder).Length > 0)
                {
                    foreach (string var in Directory.GetDirectories(folder))
                    {
                        Directory.Delete(var, true);
                    }
                }
                //删除这个目录下的所有文件
                if (Directory.GetFiles(folder).Length > 0)
                {
                    foreach (string var in Directory.GetFiles(folder))
                    {
                        File.Delete(var);
                    }
                }
            }
            catch
            {
            }

        }
    }
}
